package com.drug.mingkang.controller;

import com.drug.mingkang.service.SendSmsService;
import com.drug.mingkang.utils.ResponseMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 描述：短信处理
 *
 * @version 1.0
 * @author: wcj
 * @Date: 2020/5/13 17:26
 */
@Api(value = "短信处理控制层",tags = "短信处理Contorller")
@RestController
@CrossOrigin //跨域支持
public class SmsApiController {
    @Resource
    private SendSmsService sendSmsService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据手机号调用阿里云短信接口
     * @param phone
     * @return
     */
    @ApiOperation(value = "根据手机号调用阿里云短信接口",notes = "输入手机号",httpMethod = "GET",response = ResponseMessage.class)
    @GetMapping(value = "send/{phone}",produces = "application/json; charset=utf-8")
    public ResponseMessage code(@PathVariable("phone")String phone){
        ResponseMessage responseMessage = new ResponseMessage();
        //调用发送方法（模拟真实业务）
        String code  = stringRedisTemplate.opsForValue().get(phone);
        System.out.println("code = " + code);
        if(code!=null){
            responseMessage.setStatus(2);
            responseMessage.setMessage("该验证码还没有过期！5分钟之内有效");
            System.out.println(phone + ":" + code + "已存在，还没有过期！");
            return responseMessage;
        }
        //生成验证码并存储导redis中
        int code1 = (int) ((Math.random()*9+1)*100000);
        System.out.println("mobile_code = " + code1);
        Map map = new HashMap<>(1);
        map.put("code", code1);
       boolean isSend = sendSmsService.send(phone,"SMS_190065387",map);

       if(isSend){
           //向redis里存入数据和设置缓存时间 5分钟
           stringRedisTemplate.opsForValue().set(phone, code1+"",60*5, TimeUnit.SECONDS);
           responseMessage.setStatus(1);
           responseMessage.setMessage("验证码发送成功");
           System.out.println(phone + ":" + code1 + "发送成功");
       }else{
           responseMessage.setStatus(0);
           responseMessage.setMessage("验证码失败");
       }
        return responseMessage;
    }

}
